var server = false;
window.addEvent('domready', startGame);

function debug(heartBeatTime){
    if($defined(game.hero)){
        heartBeatTime = (new Date()).getTime() - heartBeatTime;
        game.appendLog('game.hero '+game.hero.x+'-'+game.hero.y+' zone '+game.hero.myZone.x+'-'+game.hero.myZone.y);
        if($defined(game.clickedZone)){
            var elements = game.clickedZone.getElements();
            if($defined(elements) && elements.length>=1){
                    var element = elements[0];
                    if(element.type==GAMEUNITTYPE.FAKEWALL){
                            if($defined(element.goody))
                                    game.appendLog('zoneTypes: '+game.clickedZone.types()+' element goody= '+element.goody.subtype);
                    } else {
                        game.appendLog('zoneTypes: '+game.clickedZone.types());
                    }
            } else
                    game.appendLog('freeZone');
        }
        if(heartBeatTime>game.speed-5)
          console.log('heartBeatTime too long = '+heartBeatTime+' ms');
        game.writeLog();
  }
}

/**
 * clear
 */
function clearOldLevel() {
    
    if($defined(game.heart)){
      clearTimeout(game.heart);
      game.stateCounter=0;
      game.heart=null;
      while(game.activeBombs.length>0){
            game.activeBombs[0].terminate();
      }
      while(game.heroes.length>0){
            game.heroes[0].terminate();
      }
      while(game.fakeWalls.length>0){
            game.fakeWalls[0].terminate();
      }
      while(game.walls.length>0){
            game.walls[0].terminate();
      }
      // exit remains
      while(game.goodies.length>0){
          if(game.goodies[0].subtype==GOODYSUBTYPE.EXIT){
              game.goodies[0].HTMLIncarnation.dispose();
              game.goodies[0].HTMLIncarnation.destroy();
              game.goodies[0].vaporate();
          } else
              game.goodies[0].terminate();
      }

      for(var i=0;i<game.zones.length;i++){
            game.zones[i]=null;
      }
      game.zones=[];
      game.world.resetIntoView();
    }
     game.sound.stopBombSound();
}

function generateNextLevel() {
    game.level++;
    generateLevel(game.hero.cuanta,game.hero.bombExplosionLength,game.hero.numberOfBombs,700,800,1+game.level,true);
}
function generateLevel(heroSpeed,bombExplosionLength,numberOfBombs,worldWidth,worldHeight,numberOfBadGuys,startGame){
        clearOldLevel();

	game.heroes = [];
	game.fakeWalls = [];
	game.zones = [];
	game.walls = [];
	game.goodies = [];

	if(worldWidth%game.standardWidth!=0 || worldHeight%game.standardHeight!=0){
            alert('worldWidth='+worldWidth+' must be multiple of '+game.standardWidth+' and worldHeight='+worldHeight+' must be multiple of '+game.standardHeight);
            return;
        }
	game.worldWidth=worldWidth;
	game.worldHeight=worldHeight;

        if($defined(game.world)){
            game.world.changeWorldParameters(worldWidth,worldHeight);
        } else {
            var world=new World(worldWidth,worldHeight);
            world.start();
            game.world=world;
        }

	var xZones = parseInt(game.worldWidth/game.standardWidth);
    var yZones = parseInt(game.worldHeight/game.standardHeight);
    game.zones = new Array(xZones);

    for(var i=0;i<xZones;i++){
        game.zones[i]=new Array(yZones);
        for(var j=0;j<yZones;j++){
            var zone = new StandardZone();
            zone.x=game.standardWidth*i;
            zone.y=game.standardHeight*j;
            game.zones[i][j]=zone;
        }
    }

    var xNumberOfWalls=Math.floor(xZones/2);
    var yNumberOfWalls=Math.floor(yZones/2);
    for(i=0;i<xNumberOfWalls;i++){
        for(j=0;j<yNumberOfWalls;j++){
            var wall = new Wall();
            wall.comeIntoExistence(game.world,game.standardWidth+2*i*game.standardWidth,game.standardHeight+2*j*game.standardHeight);
        }
    }

    var fakeWallsNumberOnX = Math.round(Math.random()*(xZones-3));
    for(i=0;i<yZones;i++){
      for(j=0;j<fakeWallsNumberOnX;j++){
              var xPos = Math.round(Math.random()*xZones);
              if(xPos>1)
                  xPos--;
              if((i==0 && xPos==0) || (i==0 && xPos==1) || (i==1 && xPos==0)) // the hero is here
                  continue;
              if(game.zones[xPos][i].freeZone){
                var fakeWall = new FakeWall();
                fakeWall.setGoody(null);
                fakeWall.comeIntoExistence(game.world,xPos*game.standardWidth,i*game.standardHeight);
              }
      }
    }
    //debugger;
    // always set hero at 0,0
    if(!$defined(game.hero)){
      var hero=new Hero();
      hero.setExplosionLength(bombExplosionLength);
      hero.setNumberOfBombs(numberOfBombs);
      hero.cuanta=heroSpeed;
      hero.score = parseInt($('score').get('text'));
      hero.comeIntoExistence(game.world,0,0);
      game.hero=hero;
    } else {
        game.hero.setPosition(0,0);
    }

    var contorBadGuys=0;
    for(j=0;j<yZones;j++){
        if(contorBadGuys>numberOfBadGuys)
           break;
        var doit=Math.round(Math.random()*4);
        if(doit>2){
          for(var k=0;k<xZones;k++){
              if(j<=4 && k<=4) // the hero is here so we give him some space
                  continue;
              var doit2=Math.round(Math.random()*12);
              var gameZone = game.zones[k][j];
            if(gameZone.freeZone && doit2>8){
                var badguy;
                switch(doit2){
                case 11:
                    badguy = new BadGuy();
                    break;
                case 10:
                    badguy = new ZBadGuy();
                    break;
                case 9:
                    badguy = new FBadGuy();
                    break;
                 default:
                     badguy = new IBadGuy();
                }
                badguy.comeIntoExistence(game.world,gameZone.x,gameZone.y);
                contorBadGuys++;
                if(contorBadGuys>=numberOfBadGuys)
                    break;
            }
          }
        }
    }

    if(startGame){
      game.stateCounter=0;
      if(game.heart==null)
        game.heart=setTimeout("worldbeat()",game.speed);
    }
}

function restartLevel(heroSpeed,bombExplosionLength,numberOfBombs) {
    generateLevel(heroSpeed,bombExplosionLength,numberOfBombs,700,800,3+game.level,true);
}

function initGame(){
   generateLevel(2,3,1,700,700,2,true);
}
